package bb.lanxing.lib.devices.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import bb.lanxing.lib.devices.api.ConnectionListener;
import bb.lanxing.lib.devices.api.SmartDevice;

public class ConnectionStateReceiver extends BroadcastReceiver {
    public static final String ACTION_CONNECTION_STATE_CHANGE = "action_connection_state_change";
    public static final String EXTRA_CONNECTION_ERROR = "extra_connection_error";
    public static final String EXTRA_CONNECTION_STATE = "action_connection_state";
    public static final String EXTRA_SMART_DEVICE = "extra_smart_device";
    private boolean mIsRegistered;
    private ConnectionListener mListener;

    @Override
    public final void onReceive(Context context, Intent intent) {
        if (ACTION_CONNECTION_STATE_CHANGE.equals(intent.getAction())) {
            SmartDevice smartDevice = intent.getParcelableExtra(EXTRA_SMART_DEVICE);
            int intExtra = intent.getIntExtra(EXTRA_CONNECTION_STATE, -1);
            int intExtra2 = intent.getIntExtra(EXTRA_CONNECTION_ERROR, 0);
            ConnectionListener connectionListener = this.mListener;
            if (connectionListener == null) {
                return;
            }
            connectionListener.onConnectionStateChanged(smartDevice, intExtra, intExtra2);
        }
    }

    public boolean register(Context context, ConnectionListener connectionListener) {
        if (context == null || this.mIsRegistered) {
            return false;
        }
        this.mListener = connectionListener;
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_CONNECTION_STATE_CHANGE);
        context.registerReceiver(this, intentFilter, Context.RECEIVER_EXPORTED);
        this.mIsRegistered = true;
        return true;
    }

    public void unregister(Context context) {
        if (context != null && this.mIsRegistered) {
            context.unregisterReceiver(this);
        }
        this.mIsRegistered = false;
        this.mListener = null;
    }
}
